using Prism.Mvvm;
using Prism.Commands;
using System;
using System.Windows;
using CPlatePrintSys.Application.Services;
using CPlatePrintSys.Domain.Models;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Linq;
using CPlatePrintSys.Win.Models;

namespace CPlatePrintSys.Win.ViewModels
{
    public class AddStreamShipViewModel : BindableBase
    {
        private readonly IShipConfigService _service;
        public ObservableCollection<MotherShip> MotherShips { get; }
        public MotherShip SelectedMotherShip { get; set; }
        
        private string _motherShipNo;
        public string MotherShipNo
        {
            get => _motherShipNo;
            set => SetProperty(ref _motherShipNo, value);
        }
        
        private string _streamShipNo;
        public string StreamShipNo
        {
            get => _streamShipNo;
            set => SetProperty(ref _streamShipNo, value);
        }
        
        public DelegateCommand SaveCommand { get; }
        public DelegateCommand CancelCommand { get; }

        public string Title { get; set; }   

        public bool IsEditMode { get; }
        public int StreamShipId { get; }

        public AddStreamShipViewModel(IShipConfigService service, List<MotherShip> motherShips)
        {
            Title = "添加流用船";
            _service = service;
            MotherShips = new ObservableCollection<MotherShip>(motherShips);
            SaveCommand = new DelegateCommand(OnSave);
            CancelCommand = new DelegateCommand(OnCancel);
            IsEditMode = false;
        }

        public AddStreamShipViewModel(IShipConfigService service, List<MotherShip> motherShips, ShipConfigDto dto)
        {
            Title = "编辑流用船";
            _service = service;
            MotherShips = new ObservableCollection<MotherShip>(motherShips);
            SaveCommand = new DelegateCommand(OnSave);
            CancelCommand = new DelegateCommand(OnCancel);
            IsEditMode = true;
            StreamShipNo = dto.StreamShipNo;
            MotherShipNo = dto.MotherShipNo;
            StreamShipId = dto.StreamShipId;
            SelectedMotherShip = MotherShips.FirstOrDefault(m => m.Id == dto.MotherShipId);
        }

        private async void OnSave()
        {
            if (string.IsNullOrWhiteSpace(MotherShipNo) || string.IsNullOrWhiteSpace(StreamShipNo))
            {
                MessageBox.Show("请输入母船船号和流用船号！");
                return;
            }

            // 验证船号格式（大写字母+数字）
            if (!IsValidShipNo(MotherShipNo.Trim()))
            {
                MessageBox.Show("母船船号格式不正确，应为大写字母+数字的组合！");
                return;
            }

            if (!IsValidShipNo(StreamShipNo.Trim()))
            {
                MessageBox.Show("流用船号格式不正确，应为大写字母+数字的组合！");
                return;
            }

            try
            {
                var motherShipNo = MotherShipNo.Trim().ToUpper();
                var streamShipNo = StreamShipNo.Trim().ToUpper();

                // 检查母船是否存在，如果不存在则创建
                var motherShip = MotherShips.FirstOrDefault(m => m.ShipNo == motherShipNo);
                if (motherShip == null)
                {
                    await _service.AddMotherShipAsync(motherShipNo);
                    // 重新加载母船列表
                    var allMotherShips = await _service.GetAllMotherShipsAsync();
                    MotherShips.Clear();
                    foreach (var m in allMotherShips)
                        MotherShips.Add(m);
                    motherShip = MotherShips.FirstOrDefault(m => m.ShipNo == motherShipNo);
                }

                if (IsEditMode)
                {
                    await _service.UpdateStreamShipAsync(StreamShipId, motherShip.Id);
                }
                else
                {
                    await _service.AddStreamShipAsync(streamShipNo, motherShip.Id);
                }
                CloseDialog(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}");
            }
        }

        private bool IsValidShipNo(string shipNo)
        {
            if (string.IsNullOrWhiteSpace(shipNo))
                return false;

            // 检查是否为大写字母+数字的组合
            return System.Text.RegularExpressions.Regex.IsMatch(shipNo, @"^[A-Z]+\d+$");
        }

        private void OnCancel() => CloseDialog(false);

        private void CloseDialog(bool? result)
        {
            var window = System.Windows.Application.Current.Windows.OfType<Window>().FirstOrDefault(w => w.DataContext == this);
            if (window != null)
                window.DialogResult = result;
        }
    }
} 